import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { SalaryService } from './salary.service';
import { UserService } from 'src/user/user.service';
import { WorkService } from 'src/work/work.service';
import { DeductionService } from 'src/deduction/deduction.service';
import { AttendanceService } from 'src/attendance/attendance.service';
import { Between, FindOptionsWhere, In } from 'typeorm';
import { WorkStatus } from 'src/work/work.entity';
import * as moment from 'moment';
import { UseLog } from 'src/log/useLog.decorator';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { Salary } from './Salary.entity';

@Controller('api/salary')
@UseGuards(AuthGuard("jwt"))
@ApiTags("薪资")
export class SalaryController {
    constructor(
        private readonly salaryService: SalaryService,
        private readonly userService: UserService,
        private readonly workService: WorkService,
        private readonly deductionService: DeductionService,
        private readonly attendanceService: AttendanceService
    ) { }

    @Get("mine")
    @ApiOperation({ summary: "获取我的工资表" })
    mine(
        @CurrentUser() user: UserSys
    ) {
        return this.salaryService.salary.find({
            relations: ["system", "user", "user.dept"],
            where: {
                user: {
                    id: user.id
                }
            },
            order: {
                id: "desc"
            }
        })
    }

    @Get("getAll")
    @ApiOperation({ summary: "获取某月工资列表" })
    getAll(
        @Query("time") time,
        @CurrentUser() user: UserSys
    ) {
        const where: FindOptionsWhere<Salary> = { system: { id: user.system.id } }
        if (!!time) {
            const date = moment(time).startOf("month")
            const between = Between(date.clone().toDate(), date.clone().endOf("month").toDate());
            where.publish = between
        }

        return this.salaryService.salary.find({
            where,
            relations: ["user", "system"]
        })
    }

    @Post("dels")
    @UseLog("删除工资记录")
    dels(
        @Body() { ids }
    ) {
        return this.salaryService.salary.delete({
            id: In(ids)
        })
    }

    @Get(":id/del")
    @UseLog("删除工资记录")
    del(
        @Param("id") id
    ) {
        return this.salaryService.salary.delete({
            id
        })
    }

    @Post("publish")
    @UseLog("发布工资")
    @UseGuards()
    async publish(
        @Body() { publish, data },
        @CurrentUser() user: UserSys
    ) {
        const entitys = [];
        const time = !!publish ? moment(publish).startOf("month") : moment(Date.now()).startOf("month")
        const publishTime = time.clone().add(24, "d")
        const users = await this.userService.userSys.find({
            where: {
                id: In(data.map(e => e.id))
            }
        })
        console.log(users, data)
        const system = user.system
        for (const key in data) {
            const { id, ...rest } = data[key]
            if (isNaN(id)) continue;
            const user = users.find(e => e.id == id);
            if (!user) continue;
            const between = Between(time.clone().toDate(), time.clone().endOf("month").toDate())
            await this.salaryService.salary.delete({
                publish: between,
                user: {
                    id
                }
            })
            entitys.push(this.salaryService.salary.create({
                ...rest,
                publish: publishTime.toDate(),
                user,
                system
            }))
        }
        await this.salaryService.salary.save(entitys)
    }

    @Post("userData")
    @ApiOperation({ summary: "获取用户活动信息" })
    async userData(
        @Body() {
            time
        },
        @CurrentUser() user: UserSys
    ) {
        const date = !!time ? moment(time).subtract(1, "month").startOf("month") : moment(Date.now()).subtract(1, "month").startOf("month")
        const users = await this.userService.userSys.find({
            where: {
                system: { id: user.system.id }
            },
            relations: ["system", "user", "dept"]
        });
        const result = [];
        const between = Between(date.clone().toDate(), date.clone().endOf("month").toDate())
        const works = await this.workService.work.find({
            where: {
                createAt: between,
                status: In([WorkStatus.approved, WorkStatus.done])
            },
            relations: ["user", "project"]
        })
        for (const user of users) {
            const id = user.id;
            result.push({
                score: works.reduce((sum, item) => {
                    if (item.user.id === id) {
                        return sum + item.count * item.project.score
                    }
                    return sum;
                }, 0),
                attendance: await this.attendanceService.attendance.find({
                    where: {
                        user: {
                            id
                        },
                        createAt: between
                    }
                }),
                deduction: await this.deductionService.deduction.find({
                    where: {
                        user: {
                            id
                        },
                        createAt: between
                    },
                    relations: ["project", "target"],

                }),
                user
            })
        }
        return result;
    }
}
